package com.company.genealogy.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.genealogy.web.entity.Menu;
import com.company.genealogy.web.mapper.MenuMapper;
import com.company.genealogy.web.service.MenuService;
import com.company.genealogy.web.service.RoleService;
import com.company.genealogy.web.service.UserService;
import com.company.genealogy.web.entity.Role;
import com.company.genealogy.web.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.HashSet;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {
    
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;
    
    @Override
    public List<Menu> getEnabledMenus() {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.orderByAsc("sort_order", "id");
        return list(queryWrapper);
    }
    
    @Override
    public List<Menu> getMenusByRoleId(Long roleId) {
        return baseMapper.selectMenusByRoleId(roleId);
    }
    
    @Override
    public List<Menu> getMenusByUserId(Long userId) {
        return baseMapper.selectMenusByUserId(userId);
    }
    
    @Override
    public List<Menu> buildMenuTree(List<Menu> menus) {
        if (menus == null || menus.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 按父ID分组
        Map<Long, List<Menu>> menuMap = menus.stream()
                .collect(Collectors.groupingBy(Menu::getParentId));
        
        // 获取顶级菜单
        List<Menu> rootMenus = menuMap.getOrDefault(0L, new ArrayList<>());
        
        // 递归构建树
        for (Menu menu : rootMenus) {
            buildMenuTreeRecursive(menu, menuMap);
        }
        
        return rootMenus;
    }
    
    private void buildMenuTreeRecursive(Menu parent, Map<Long, List<Menu>> menuMap) {
        List<Menu> children = menuMap.get(parent.getId());
        if (children != null && !children.isEmpty()) {
            parent.setChildren(children);
            for (Menu child : children) {
                buildMenuTreeRecursive(child, menuMap);
            }
        } else {
            parent.setChildren(new ArrayList<>());
        }
    }

    @Override
    public List<Menu> getMenuTreeByUsername(String username) {
        User user = userService.getByUsername(username);
        if (user == null) {
            return new ArrayList<>();
        }
        List<Role> roles = roleService.getRolesByUserId(user.getId());
        HashSet<Long> menuIdSet = new HashSet<>();
        List<Menu> allMenus = new ArrayList<>();
        for (Role role : roles) {
            List<Menu> menus = baseMapper.selectMenusByRoleId(role.getId());
            for (Menu m : menus) {
                if (menuIdSet.add(m.getId())) {
                    allMenus.add(m);
                }
            }
        }
        // 只返回启用状态菜单
        List<Menu> enabledMenus = allMenus.stream().filter(m -> m.getStatus() != null && m.getStatus() == 1).collect(java.util.stream.Collectors.toList());
        return buildMenuTree(enabledMenus);
    }
} 